import os

def find_and_rename_files(folder_path, prefix):
    # 获取文件夹中所有文件
    files = os.listdir(folder_path)

    # 提取具有指定前缀的文件
    matching_files = [file for file in files if file.startswith(prefix)]

    # 找到文件中的最大编号
    max_index = 0
    for file in matching_files:
        try:
            file_index = int(file[len(prefix):-len(".txt")])
            max_index = max(max_index, file_index)
        except ValueError:
            pass

    # 找到缺失的编号并重命名文件
    for i in range(1, max_index):
        original_filename = f"{prefix}{i:03d}.txt"
        new_filename = f"{prefix}{i + 1:03d}.txt"

        if original_filename not in matching_files and new_filename in matching_files:
            old_path = os.path.join(folder_path, new_filename)
            new_path = os.path.join(folder_path, original_filename)

            # 重命名文件
            os.rename(old_path, new_path)
            print(f"Renamed: {new_filename} to {original_filename}")


# 指定文件夹路径和文件前缀
folder_path = '/path/to/your/folder'
file_prefix = 'spam'

# 调用函数查找并重命名文件
find_and_rename_files(folder_path, file_prefix)
